﻿namespace HTMLConverter.Xml
{
    using System.Xml.Linq;

    internal class XmlElement : XElement
    {
        public XmlElement(string name, string namespaceURI) : base(XName.Get(name, namespaceURI)) { }

        #region properties

        public string OuterXml
        {
            get
            {
                return this.ToString();
            }
        }

        public string LocalName
        {
            get
            {
                if (Name == null)
                {
                    return string.Empty;
                }

                return Name.LocalName;
            }
        }

        public string LowerName
        {
            get
            {
                return LocalName.ToLower();
            }
        }

        public XmlElement FirstChild
        {
            get
            {
                if (FirstNode is XmlElement)
                {
                    return FirstNode as XmlElement;
                }
                return null;
            }
        }

        public XmlElement LastChild
        {
            get
            {
                if (LastNode is XmlElement)
                {
                    return LastNode as XmlElement;
                }
                return null;
            }
        }

        #endregion

        public XNode AppendChild(XNode newChild)
        {
            Add(newChild);
            return newChild;
        }

        public void SetAttribute(XName name, string value)
        {
            base.SetAttributeValue(name, value);
        }

        public string GetAttribute(string attributeName)
        {
            attributeName = attributeName.ToLower();

            foreach (var attribute in Attributes())
            {
                if (attribute.Name.LocalName.ToLower() == attributeName)
                {
                    return attribute.Value;
                }
            }

            return null;
        }
    }
}
